package cn.tedu.sp02.controller;

import java.util.List;
import java.util.Random;

import cn.tedu.sp01.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;


@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Value("${server.port}")
    private int port;

    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("server.port=" + port + ", orderId=" + orderId);

        List<Item> items = itemService.getItems(orderId);
        //做一个业务,随机阻塞 90%概率执行阻塞代码
        if(Math.random()<0.9){
            //随机延迟时长  0到5秒
            int i = new Random().nextInt(5000);
            log.info("延迟:  "+i);
            Thread.sleep(i);
        }
        return JsonResult.ok(items).msg("port=" + port);
    }

    @PostMapping("/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {
        itemService.decreaseNumber(items);
        return JsonResult.ok();
    }

    @GetMapping("/favicon.ico")
    public void ico(){

    }
}
